package com.zhkj.txg.module.order.popup

import android.content.Context
import android.view.Gravity
import android.view.View
import android.view.animation.Animation
import android.widget.TextView
import com.zhkj.lib.utils.SpanUtil
import com.zhkj.txg.R
import com.zhkj.txg.module.order.entity.OrderPayEntity
import com.zhkj.txg.module.order.entity.OrderSubmitEntity
import razerdp.basepopup.BasePopupWindow

class PayTypePopupWindow(
    context: Context,
    val onPay: (type: String, orderInfo: OrderSubmitEntity) -> Unit,
    val onCancel: () -> Boolean
) : BasePopupWindow(context) {

    private var btnAliPay: View? = null
    private var btnWxPay: View? = null
    private var btnBalancePay: View? = null
    private var btnPay: TextView? = null

    private var orderInfo: OrderSubmitEntity? = null

    init {
        popupGravity = Gravity.BOTTOM
        setOutSideDismiss(false)
    }

    override fun onCreateContentView(): View = createPopupById(R.layout.popup_pay_type)

    override fun onCreateShowAnimation(): Animation = getTranslateVerticalAnimation(1f, 0f, 300)

    override fun onCreateDismissAnimation(): Animation = getTranslateVerticalAnimation(0f, 1f, 300)

    override fun onViewCreated(contentView: View?) {
        contentView?.findViewById<View>(R.id.ivClose)?.setOnClickListener {
            if (!onCancel()) dismiss()
        }
        btnBalancePay = contentView?.findViewById(R.id.btnBalancePay)
        btnAliPay = contentView?.findViewById(R.id.btnAliPay)
        btnWxPay = contentView?.findViewById(R.id.btnWxPay)
        btnPay = contentView?.findViewById(R.id.btnPay)
        btnBalancePay?.setOnClickListener {
            it.isSelected = true
            btnWxPay?.isSelected = false
            btnAliPay?.isSelected = false
        }
        btnAliPay?.setOnClickListener {
            it.isSelected = true
            btnWxPay?.isSelected = false
            btnBalancePay?.isSelected = false
        }
        btnWxPay?.setOnClickListener {
            it.isSelected = true
            btnAliPay?.isSelected = false
            btnBalancePay?.isSelected = false
        }
        btnPay?.setOnClickListener {
            orderInfo?.let {
                onPay(
                    when {
                        btnAliPay?.isSelected == true -> OrderPayEntity.TYPE_ALIPAY
                        btnWxPay?.isSelected == true -> OrderPayEntity.TYPE_WECHAT
                        else -> OrderPayEntity.TYPE_BALANCE
                    }, it
                )
            }
        }
    }

    override fun onBackPressed(): Boolean {
        return onCancel()
    }

    fun setData(it: OrderSubmitEntity) {
        orderInfo = it
        btnPay?.text = SpanUtil.setPrefixMoneyStr("立即支付", it.orderAmount.toString())
        btnBalancePay?.performClick()
    }
}